// profile_editor_dialog.cpp
#include "profile_editor_dialog.h"
#include <wx/sizer.h>
#include <wx/statline.h>
#include <wx/msgdlg.h>

wxBEGIN_EVENT_TABLE(ProfileEditorDialog, wxDialog)
    EVT_BUTTON(wxID_OK, ProfileEditorDialog::OnOK)
    EVT_BUTTON(wxID_CANCEL, ProfileEditorDialog::OnCancel)
    EVT_CHOICE(wxID_ANY, ProfileEditorDialog::OnSettingChanged)
    EVT_TEXT(wxID_ANY, ProfileEditorDialog::OnSettingChanged)
    EVT_CHECKBOX(wxID_ANY, ProfileEditorDialog::OnSettingChanged)
    EVT_LISTBOX(wxID_ANY, ProfileEditorDialog::OnProfileSelected)
    EVT_BUTTON(wxID_ANY, ProfileEditorDialog::OnDuplicate)
    EVT_BUTTON(wxID_ANY, ProfileEditorDialog::OnDelete)
wxEND_EVENT_TABLE()

ProfileEditorDialog::ProfileEditorDialog(wxWindow* parent, 
                                       const wxString& profileId,
                                       bool isNew)
    : wxDialog(parent, wxID_ANY, "Build Profile Editor", 
               wxDefaultPosition, wxSize(600, 500)),
      m_isNewProfile(isNew)
{
    CreateControls();
    
    if (!profileId.empty()) {
        LoadProfile(profileId);
    } else {
        // 新建配置，使用默认值
        m_currentProfile = ProfileManager::Get().CreateDesktopDebug();
        m_currentProfile.name = "New_Profile";
    }
    
    UpdatePreview();
}

void ProfileEditorDialog::CreateControls() {
    wxBoxSizer* mainSizer = new wxBoxSizer(wxVERTICAL);
    
    // 创建笔记本控件
    wxNotebook* notebook = new wxNotebook(this, wxID_ANY);
    
    CreateBasicPage(notebook);
    CreateAdvancedPage(notebook);
    CreatePreviewPage(notebook);
    
    mainSizer->Add(notebook, 1, wxEXPAND | wxALL, 5);
    
    // 按钮区域
    wxBoxSizer* buttonSizer = new wxBoxSizer(wxHORIZONTAL);
    
    m_duplicateBtn = new wxButton(this, wxID_ANY, "Duplicate");
    m_deleteBtn = new wxButton(this, wxID_ANY, "Delete");
    
    buttonSizer->Add(m_duplicateBtn, 0, wxRIGHT, 5);
    buttonSizer->Add(m_deleteBtn, 0, wxRIGHT, 5);
    buttonSizer->AddStretchSpacer();
    buttonSizer->Add(new wxButton(this, wxID_CANCEL, "Cancel"), 0, wxRIGHT, 5);
    buttonSizer->Add(new wxButton(this, wxID_OK, "OK"), 0);
    
    mainSizer->Add(new wxStaticLine(this), 0, wxEXPAND | wxALL, 5);
    mainSizer->Add(buttonSizer, 0, wxEXPAND | wxALL, 5);
    
    SetSizer(mainSizer);
}

void ProfileEditorDialog::CreateBasicPage(wxNotebook* notebook) {
    wxPanel* page = new wxPanel(notebook);
    wxFlexGridSizer* grid = new wxFlexGridSizer(2, 5, 5);
    grid->AddGrowableCol(1);
    
    // 配置名称
    grid->Add(new wxStaticText(page, wxID_ANY, "Profile Name:"), 0, wxALIGN_CENTER_VERTICAL);
    m_nameText = new wxTextCtrl(page, wxID_ANY);
    grid->Add(m_nameText, 1, wxEXPAND);
    
    // 构建变体
    grid->Add(new wxStaticText(page, wxID_ANY, "Build Variant:"), 0, wxALIGN_CENTER_VERTICAL);
    m_variantChoice = new wxChoice(page, wxID_ANY);
    m_variantChoice->Append("Debug");
    m_variantChoice->Append("Release");
    m_variantChoice->Append("Profile");
    m_variantChoice->Append("Size Optimized");
    m_variantChoice->Append("Performance");
    grid->Add(m_variantChoice, 1, wxEXPAND);
    
    // 目标操作系统
    grid->Add(new wxStaticText(page, wxID_ANY, "Target OS:"), 0, wxALIGN_CENTER_VERTICAL);
    m_osChoice = new wxChoice(page, wxID_ANY);
    m_osChoice->Append("Windows");
    m_osChoice->Append("Linux");
    m_osChoice->Append("macOS");
    m_osChoice->Append("Android");
    m_osChoice->Append("Embedded");
    m_osChoice->Append("WebAssembly");
    grid->Add(m_osChoice, 1, wxEXPAND);
    
    // 目标架构
    grid->Add(new wxStaticText(page, wxID_ANY, "Architecture:"), 0, wxALIGN_CENTER_VERTICAL);
    m_archChoice = new wxChoice(page, wxID_ANY);
    m_archChoice->Append("32-bit");
    m_archChoice->Append("64-bit");
    m_archChoice->Append("ARM64");
    m_archChoice->Append("RISC-V 32");
    m_archChoice->Append("RISC-V 64");
    grid->Add(m_archChoice, 1, wxEXPAND);
    
    // 工具链
    grid->Add(new wxStaticText(page, wxID_ANY, "Toolchain:"), 0, wxALIGN_CENTER_VERTICAL);
    m_toolchainChoice = new wxChoice(page, wxID_ANY);
    m_toolchainChoice->Append("GCC");
    m_toolchainChoice->Append("Clang");
    m_toolchainChoice->Append("MSVC");
    m_toolchainChoice->Append("MinGW");
    m_toolchainChoice->Append("ARM GCC");
    m_toolchainChoice->Append("RISC-V GCC");
    m_toolchainChoice->Append("Emscripten");
    grid->Add(m_toolchainChoice, 1, wxEXPAND);
    
    page->SetSizer(grid);
    notebook->AddPage(page, "Basic Settings");
}

void ProfileEditorDialog::CreateAdvancedPage(wxNotebook* notebook) {
    wxPanel* page = new wxPanel(notebook);
    wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);
    
    // 浮点精度
    wxBoxSizer* floatSizer = new wxBoxSizer(wxHORIZONTAL);
    floatSizer->Add(new wxStaticText(page, wxID_ANY, "Float Precision:"), 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, 5);
    m_floatChoice = new wxChoice(page, wxID_ANY);
    m_floatChoice->Append("Software");
    m_floatChoice->Append("Single (FP32)");
    m_floatChoice->Append("Double (FP64)");
    m_floatChoice->Append("Half (FP16)");
    m_floatChoice->Append("Tensor");
    floatSizer->Add(m_floatChoice, 1, wxEXPAND);
    sizer->Add(floatSizer, 0, wxEXPAND | wxBOTTOM, 5);
    
    // C++ 标准
    wxBoxSizer* stdSizer = new wxBoxSizer(wxHORIZONTAL);
    stdSizer->Add(new wxStaticText(page, wxID_ANY, "C++ Standard:"), 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, 5);
    m_stdChoice = new wxChoice(page, wxID_ANY);
    m_stdChoice->Append("C++11");
    m_stdChoice->Append("C++14");
    m_stdChoice->Append("C++17");
    m_stdChoice->Append("C++20");
    m_stdChoice->Append("C++23");
    stdSizer->Add(m_stdChoice, 1, wxEXPAND);
    sizer->Add(stdSizer, 0, wxEXPAND | wxBOTTOM, 5);
    
    // 语言特性
    wxStaticBox* langBox = new wxStaticBox(page, wxID_ANY, "Language Features");
    wxStaticBoxSizer* langSizer = new wxStaticBoxSizer(langBox, wxVERTICAL);
    
    m_exceptionsCheck = new wxCheckBox(langBox, wxID_ANY, "Enable Exceptions");
    m_rttiCheck = new wxCheckBox(langBox, wxID_ANY, "Enable RTTI");
    
    langSizer->Add(m_exceptionsCheck, 0, wxALL, 2);
    langSizer->Add(m_rttiCheck, 0, wxALL, 2);
    sizer->Add(langSizer, 0, wxEXPAND | wxBOTTOM, 5);
    
    // 自定义标志
    wxStaticBox* flagsBox = new wxStaticBox(page, wxID_ANY, "Custom Compiler Flags");
    wxStaticBoxSizer* flagsSizer = new wxStaticBoxSizer(flagsBox, wxVERTICAL);
    
    m_customFlagsText = new wxTextCtrl(flagsBox, wxID_ANY, "", 
                                      wxDefaultPosition, wxDefaultSize,
                                      wxTE_MULTILINE);
    flagsSizer->Add(m_customFlagsText, 1, wxEXPAND);
    sizer->Add(flagsSizer, 1, wxEXPAND);
    
    page->SetSizer(sizer);
    notebook->AddPage(page, "Advanced Settings");
}

void ProfileEditorDialog::CreatePreviewPage(wxNotebook* notebook) {
    wxPanel* page = new wxPanel(notebook);
    wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);
    
    // 现有配置列表
    wxBoxSizer* listSizer = new wxBoxSizer(wxHORIZONTAL);
    listSizer->Add(new wxStaticText(page, wxID_ANY, "Existing Profiles:"), 0, wxALIGN_CENTER_VERTICAL | wxRIGHT, 5);
    
    m_profilesList = new wxListBox(page, wxID_ANY);
    auto profiles = ProfileManager::Get().GetAllProfiles();
    for (const auto& profile : profiles) {
        m_profilesList->Append(profile.name);
    }
    listSizer->Add(m_profilesList, 1, wxEXPAND);
    
    sizer->Add(listSizer, 1, wxEXPAND | wxBOTTOM, 5);
    
    // 预览区域
    wxStaticBox* previewBox = new wxStaticBox(page, wxID_ANY, "Configuration Preview");
    wxStaticBoxSizer* previewSizer = new wxStaticBoxSizer(previewBox, wxVERTICAL);
    
    m_previewText = new wxTextCtrl(previewBox, wxID_ANY, "", 
                                  wxDefaultPosition, wxDefaultSize,
                                  wxTE_MULTILINE | wxTE_READONLY);
    previewSizer->Add(m_previewText, 1, wxEXPAND);
    
    sizer->Add(previewSizer, 1, wxEXPAND);
    
    page->SetSizer(sizer);
    notebook->AddPage(page, "Preview & Selection");
}

void ProfileEditorDialog::LoadProfile(const wxString& profileId) {
    auto& manager = ProfileManager::Get();
    auto* profile = manager.GetProfile(profileId);
    
    if (profile) {
        m_currentProfile = *profile;
        
        // 更新UI控件
        m_nameText->SetValue(m_currentProfile.name);
        m_variantChoice->SetSelection(static_cast<int>(m_currentProfile.variant));
        m_osChoice->SetSelection(static_cast<int>(m_currentProfile.os));
        m_archChoice->SetSelection(static_cast<int>(m_currentProfile.architecture));
        m_toolchainChoice->SetSelection(static_cast<int>(m_currentProfile.compiler));
        m_floatChoice->SetSelection(static_cast<int>(m_currentProfile.floatPrecision));
        m_stdChoice->SetStringSelection(m_currentProfile.stdVersion);
        m_exceptionsCheck->SetValue(m_currentProfile.enableExceptions);
        m_rttiCheck->SetValue(m_currentProfile.enableRTTI);
        m_customFlagsText->SetValue(m_currentProfile.customFlags);
    }
}

void ProfileEditorDialog::UpdatePreview() {
    wxString preview;
    
    preview << "Profile: " << m_currentProfile.name << "\n\n";
    preview << "Build Variant: " << EnumConverter::ToString(m_currentProfile.variant) << "\n";
    preview << "Target OS: " << EnumConverter::ToString(m_currentProfile.os) << "\n";
    preview << "Architecture: " << EnumConverter::ToString(m_currentProfile.architecture) << "\n";
    preview << "Toolchain: " << EnumConverter::ToString(m_currentProfile.compiler) << "\n";
    preview << "Float Precision: " << EnumConverter::ToString(m_currentProfile.floatPrecision) << "\n";
    preview << "C++ Standard: " << m_currentProfile.stdVersion << "\n\n";
    
    preview << "Compiler Flags:\n";
    auto flags = m_currentProfile.GetCompilerFlags();
    for (const auto& flag : flags) {
        preview << "  " << flag << "\n";
    }
    
    m_previewText->SetValue(preview);
}

void ProfileEditorDialog::OnSettingChanged(wxCommandEvent& event) {
    // 从UI更新配置对象
    m_currentProfile.name = m_nameText->GetValue();
    m_currentProfile.variant = static_cast<BuildVariant>(m_variantChoice->GetSelection());
    m_currentProfile.os = static_cast<OSFamily>(m_osChoice->GetSelection());
    m_currentProfile.architecture = static_cast<ArchBits>(m_archChoice->GetSelection());
    m_currentProfile.compiler = static_cast<Toolchain>(m_toolchainChoice->GetSelection());
    m_currentProfile.floatPrecision = static_cast<FloatMode>(m_floatChoice->GetSelection());
    m_currentProfile.stdVersion = m_stdChoice->GetStringSelection();
    m_currentProfile.enableExceptions = m_exceptionsCheck->GetValue();
    m_currentProfile.enableRTTI = m_rttiCheck->GetValue();
    m_currentProfile.customFlags = m_customFlagsText->GetValue();
    
    // 同步传统字段
    m_currentProfile.SyncToLegacy();
    
    UpdatePreview();
    event.Skip();
}

void ProfileEditorDialog::OnProfileSelected(wxCommandEvent& event) {
    int selection = m_profilesList->GetSelection();
    if (selection != wxNOT_FOUND) {
        wxString profileName = m_profilesList->GetString(selection);
        LoadProfile(profileName + "_0"); // 简化ID生成
    }
}

void ProfileEditorDialog::OnOK(wxCommandEvent& event) {
    if (!ValidateInput()) {
        return;
    }
    
    SaveProfile();
    EndModal(wxID_OK);
}

void ProfileEditorDialog::OnCancel(wxCommandEvent& event) {
    EndModal(wxID_CANCEL);
}

void ProfileEditorDialog::OnDuplicate(wxCommandEvent& event) {
    wxString newName = m_currentProfile.name + "_Copy";
    if (ProfileManager::Get().DuplicateProfile(m_currentProfile.GetId(), newName)) {
        wxMessageBox("Profile duplicated successfully!", "Success", wxOK | wxICON_INFORMATION);
        // 刷新列表
        m_profilesList->Clear();
        auto profiles = ProfileManager::Get().GetAllProfiles();
        for (const auto& profile : profiles) {
            m_profilesList->Append(profile.name);
        }
    }
}

void ProfileEditorDialog::OnDelete(wxCommandEvent& event) {
    if (wxMessageBox("Are you sure you want to delete this profile?", "Confirm Delete", 
                    wxYES_NO | wxICON_QUESTION) == wxYES) {
        if (ProfileManager::Get().DeleteProfile(m_currentProfile.GetId())) {
            wxMessageBox("Profile deleted successfully!", "Success", wxOK | wxICON_INFORMATION);
            EndModal(wxID_OK);
        }
    }
}

bool ProfileEditorDialog::ValidateInput() {
    if (m_nameText->GetValue().empty()) {
        wxMessageBox("Profile name cannot be empty!", "Validation Error", wxOK | wxICON_ERROR);
        return false;
    }
    
    auto errors = ProfileManager::Get().GetValidationErrors(m_currentProfile);
    if (!errors.empty()) {
        wxString errorMsg = "Configuration errors:\n";
        for (const auto& error : errors) {
            errorMsg += "• " + error + "\n";
        }
        wxMessageBox(errorMsg, "Validation Error", wxOK | wxICON_ERROR);
        return false;
    }
    
    return true;
}

void ProfileEditorDialog::SaveProfile() {
    auto& manager = ProfileManager::Get();
    
    if (m_isNewProfile) {
        manager.CreateProfile(m_currentProfile);
    } else {
        manager.UpdateProfile(m_currentProfile);
    }
}
